package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> lists() {
        return regionRepository.findAll();
    }
    //分页查询
    @Override
    public Page<Region> query(RegionQuery qo) {
        //创建查询对象
        Query query = new Query();
        //通过查询拿到总条数
        long count = mongoTemplate.count(query, Region.class);
        //判断有没有数据
        if (count==0){
            return Page.empty();//返回一个空,页面不会错,如果直接返回一个0页面就会报错
        }
        //无条件分页
        PageRequest request = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //查询所有数据
        query.with(request);
        List<Region> list = mongoTemplate.find(query, Region.class);
        return new PageImpl<>(list,request,count);
    }

    @Override
    public Region findById(String rid) {
        return this.get(rid);
    }

    @Override
    public List<Region> queryHor() {
        //根据状态,用序号排序
        return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }

}
